<?php

namespace App\Http\Controllers\Admin;

use App\Jobs\MarketingData;
use App\Models\ActivitySale;
use App\Models\Marketing;
use App\Models\User;
use App\Models\UserAccount;
use App\Models\UserLevel;
use App\Models\UserReward;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\LayuiController as Layui;
use App\Exceptions\FormException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Validator;

class MarketingController extends Controller
{
    /**
     * 列表页面
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @return   [type]     [description]
     */
    public function index()
    {
        return view('Admin.marketing.index');
    }

    /**
     * 获取数据
     * @return [json]           [数组格式]
     */
    public function table(Request $request)
    {
        $payload = $request->all();
        $activityData = Marketing::with('activity')->orderBy('id', 'DESC')
            ->where(function ($query) use ($payload) {
                if (isset($payload['start_at']) && $payload['start_at'] != '') {
                    $query->Where('start_at', '>=', $payload['start_at']);
                    $query->Where('start_at', '<=', $payload['start_at'] . ' 24:59:59');
                }
                if (isset($payload['status']) && $payload['status'] != '') {
                    $query->Where('status', '=', $payload['status']);
                }
            })
            ->paginate($request->get('limit', 10));
        return Layui::tableJson($activityData, 0, 1);
    }


    /**
     * 添加页面
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function create()
    {
        if (View::exists('Admin/marketing/add')) {

            $data['activity'] = ActivitySale::where([['activity_type', ActivitySale::TYPE_TWO], ['status', ActivitySale::STATUS_TRUE], ['issue_type', 1]])->select('id', 'activity_name')->get();
            $data['level'] = UserLevel::where('status', UserLevel::STATUS_YES)->select('id', 'level_name')->get();
            return view('Admin/marketing/add', $data);
        } else {
            return 'View Not Found';
        }
    }

    /**
     * 添加请求
     *
     * @Author   stonefall
     * @DateTime 2019-06-5
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function store(Request $request)
    {

        $payload = $request->all(['activity_sale_id', 'number', 'rule_type', 'level', 'user_list', 'start_at', 'end_at']);

        $rule = [
            'activity_sale_id' => 'required|numeric',
            'number' => ['required', 'numeric', function ($attribute, $value, $fail) {
                if ($value) {
                    if (!preg_match('/^[0-9]+$/', $value)) {
                        return $fail('每人最大发放数量请输入数字');
                    }
                }
            }],
            'rule_type' => 'required|in:1,2,3',//
            'level' => 'required_if:rule_type,2',
            'user_list' => 'required_if:rule_type,1',


        ];
        $message = [
            'activity_sale_id.required' => '请选择优惠券活动',
            'number.required' => '请输入每人最大发放数量',
            'number.numeric' => '每人最大发放数量请输入数字',
            'rule_type.required' => '请选择优惠类型',
            'rule_type.in' => '优惠类型不再选择范围内',
            'level.required_if' => '请选择会员等级',
            'user_list.required_if' => '请选择指定用户',
        ];
        Validator::make($payload, $rule, $message)->validate();
        $activitySale = ActivitySale::find($payload['activity_sale_id']);
        $payload['activity_name'] = $activitySale->activity_name;
        $payload['type'] = $payload['rule_type'];
        $payload['start_at'] = date('Y-m-d H:i:s');
        if (strtotime($activitySale->end_at) + 86400 < time()) {
            throw new FormException('优惠券已失效，不可发放' . $activitySale->end_at);
        }
        switch ($payload['type']) {
            case 1:
                $payload['scope'] = $payload['user_list'];
                $payload['scope_title'] = substr_count($payload['user_list'], ',') . '人';
                break;
            case 2:
                $level = '';
                $level_name = '';
                foreach ($payload['level'] as $item => $value) {
                    $level .= $value . ',';
                    $name = UserLevel::find($value)->level_name;
                    if ((count($payload['level']) - 1) == $item) {
                        $level_name .= ($name == '粉丝') ? $name : $name . '级会员';
                    } else {
                        $level_name .= ($name == '粉丝') ? $name . '、' : $name . '级会员、';
                    }
                }
                $payload['scope'] = $level;
                $payload['scope_title'] = $level_name;
                break;
            case 3:
                $payload['scope'] = 'all';
                $payload['scope_title'] = '全部用户';
                break;
        }
        unset($payload['rule_type'], $payload['level'], $payload['user_list']);
        try {
            $marketing = Marketing::create($payload);
        } catch (\Exception $exception) {
            throw new FormException(\App::environment('local') ? $exception->getMessage() : '保存失败');
        }
        $number = 1000;
        for ($j = 0; $j < $payload['number']; $j++) {
            switch ($marketing->type) {
                case 1:
                    $value = explode(',', $marketing->scope);
                    $user_number = User::whereIn('id', $value)->count('id');
                    $page = ceil($user_number / $number);
                    for ($i = 0; $i < $page; $i++) {
                        $user_list = User::whereIn('id', $value)->skip($i * $number)->take($number)->get(['id'])->toArray();
                        $status = ($i + 1 == $page);
                        dispatch(new MarketingData($marketing,$marketing->id, $user_list, $status));
                    }
                    break;
                case 2:
                    $value = explode(',', $marketing->scope);
                    $user_number = UserAccount::whereIn('user_level_id', $value)->count('id');
                    $page = ceil($user_number / $number);
                    for ($i = 0; $i < $page; $i++) {
                        $user_list = UserAccount::whereIn('user_level_id', $value)->skip($i * $number)->take($number)->get(['id','user_id'])->toArray();
                        $status = ($i + 1 == $page);
                        $marketing_id = $marketing->id;
                        dispatch(new MarketingData($marketing,$marketing_id, $user_list, $status));
                    }
                    break;
                case 3:
                    $user_number = User::count('id');
                    $page = ceil($user_number / $number);
                    for ($i = 0; $i < $page; $i++) {
                        $user_list = User::skip($i * $number)->take($number)->get(['id'])->toArray();
                        $status = ($i + 1 == $page);
                        $marketing_id = $marketing->id;
                        dispatch(new MarketingData($marketing,$marketing_id, $user_list, $status));
                    }
                    break;
                default:
                    return false;
            }
        }
        return $this->getResponseSuccess('保存成功', route('marketing.index'));
    }
}
